class AuthController < ApplicationController

  skip_before_filter :check_auth, :only => [:logout]
  
  def check_auth
    redirect_to :controller => 'game', :action => 'game' if cookies[:authentificated]
  end

  def register
    user = User.find_last_by_login(params[:reg_login])
    response.headers["Content-Type"] = "application/json"
    respond_to do |format|
      if user.nil? && !(params[:reg_login].nil? || params[:reg_pass].nil?)
        User.new(:login => params[:reg_login], :password => params[:reg_pass], :money => 1000).save
        user = User.find_last_by_login(params[:reg_login])
        cookies[:current_user_id] = user.id
        cookies[:username] = user.login
        cookies[:authentificated] = true
        format.json {render :json => '{ "state":true, "money":' + user.money.to_s + ' }'}
      else
        format.json {render :json => '{ "state":false }'}
      end
    end
  end

  def login
    user = User.find_last_by_login(params[:login_login])
    response.headers["Content-Type"] = "application/json"
    respond_to do |format|
      if !user.nil? && user.password.eql?(params[:login_pass])
        if user.money == nil
          user.money = 1000
          user.update
        end
        cookies[:current_user_id] = user.id
        cookies[:username] = user.login
        cookies[:authentificated] = true
        format.json {render :json => '{ "state":true, "money":' << user.money.to_s << ' }'}
      else
        format.json {render :json => '{ "state":false }'}
      end
    end
  end

    def logout
    cookies.delete(:authentificated)
    cookies.delete(:username)
    cookies.delete(:current_user_id)
    redirect_to :controller => 'auth', :action => 'auth'
  end

end
